//
//  StudyCoureVideoViewController.m
//  LovingPartyBuilding
//
//  Created by ZJ on 2017/6/1.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "StudyCoureVideoViewController.h"
#import "ZJStudyCoureFooterView.h"
#import "SkinVideoViewController.h"
#import "ZJVideoControllerMeunView.h"
#import "ZJSCNoteModel.h"
#import "ZJSCSynopsisModel.h"
#import "ZJSCQusetionsSrectionModel.h"

#import "StudyCourseNoteViewController.h"
#import "StudyCourseQuestionsViewController.h"
#import "SendCommentView.h"
#import <IQKeyboardManager.h>
/** 课程推荐、猜你喜欢 */
#import "ZJCourseRecommendView.h"
/** 相关课程 */
#import "ZJCorrelationCourseTableViewCell.h"
/** 课程cell */
#import "ZJStudyCourseSynopsisTableViewCell.h"
#import "ZJStudyCourseSynopsisTableViewCellModel.h"

#import "ZJStudySpacialDetailModel.h"
#import "ZJSCSynopsisGradeModel.h"
#define  CorrelationCourseCELL @"ZJCorrelationCourseTableViewCell"
#define SYNOPSISSCECTIONVIEW @"ZJStudyCourseSynopsisTableViewCell.h"


@interface StudyCoureVideoViewController ()<UITableViewDelegate,UITableViewDataSource,ZJStudyCoureFooterViewDelegate,ZJVideoControllerMeunViewDelegate,SendCommentViewDelegate,UIGestureRecognizerDelegate,SkinVideoViewControllerDelegate,ZJCorrelationCourseTableViewCellDelegate,ZJCRImageViewAndLabelViewDelegate,ZJStudyCourseSynopsisTableViewCellDelegate>
{
    UIView *_commentBGView;/** 评论页面背景View */
    BOOL _isCourseComment;/**< 判断是否是课程评论、还是评论-评论 */
    BOOL _isCommentORNote;/**< YES:评论 NO:笔记 */
    NSMutableDictionary *cellHeightDict;/**< 记录cell的高度 */
    /**< 课程简介是否展开  yes:展开  NO  收缩 */
    BOOL _synopsisIntroduce_isUnfold;
    /**< 教师简介是否展开  yes:展开  NO  收缩 */
    BOOL _teacherIntroduce_isUnfold;
    NSString *_COLLECTION_ID;/**< 选学表ID */
}
/** 视频播放控制器 */
@property (nonatomic, strong)  SkinVideoViewController *videoPlayer;
/** 视频下部控制器 */
@property (nonatomic, strong) ZJVideoControllerMeunView *videoPlayerMeun;
/** 下面的控制器 */
@property (nonatomic, strong) ZJStudyCoureFooterView *footerView;
/** tableview表的数据 */
@property (nonatomic, strong) NSMutableArray *dataArray;
/** tableviewFooterView的数据 */
@property (nonatomic, strong) NSMutableArray *tableFooterDataArray;
/** tableview */
@property (nonatomic, strong) UITableView *tableView;
/** tableViewFootView */
@property (nonatomic, strong) ZJCourseRecommendView *tableFooterViwe;

/** 评论模块 */
@property (nonatomic, strong) SendCommentView *sendCommentView;
/**  判断是否加入选学  */
@property (strong, nonatomic) NSString  *isCollection;
/**  评分详情  */
@property (strong, nonatomic) ZJSCSynopsisGradeModel  *gradeModel;
/**  判断是否评分  */
@property (assign, nonatomic) BOOL   isScore;

@end

@implementation StudyCoureVideoViewController
- (void)viewDidDisappear:(BOOL)animated {
    if (!self.navigationController.viewControllers) {
        // 主动调用 cancel 方法销毁播放器
        [self.videoPlayer cancel];    // cancel方法中调用了cancelObserver
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    if (self.isModel) {
        [self.videoPlayer cancel];
    }
    
    [super viewDidDisappear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.block) {
        self.model.CLICKRATE = [NSString stringWithFormat:@"%ld",[self.model.CLICKRATE integerValue] + 1];
        self.block(self.model);
    }
    //关闭右滑pop
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
    //关闭右滑pop
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    cellHeightDict = [NSMutableDictionary dictionary];
    [self netGradeInfor];
    [self networking_introduce];
    [self netWorking_Recommend];
    [self setupUI];
    self.navigationController.navigationBar.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(currentTimeAndTotalTime:) name:ZJVideoControllerMeunViewTime object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];/**< 键盘将要出现的通知 */
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object:nil];/**< 键盘将要消失的通知 */
    
    //接受简介cell刷新
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(IntroduceCell_reLoadTableViewCell:) name:INTRODUCECELL_RELOAD object:nil];
    
    self.titlelabel.text = self.model.NAME;
    [self netWorking_lastVideo];
    
    ///存本地
    [[NSUserDefaults standardUserDefaults] setObject:[self.model yy_modelToJSONObject] forKey:LastVideoDict];
}
- (void)setupUI{
    [self.view addSubview:self.footerView];
   
    [self.view addSubview:self.tableView];
    [self initVideoPlayer];
    
     [self.videoPlayer.videoControl.contentView addSubview:self.videoPlayerMeun];
    
    self.videoPlayerMeun.sd_layout
    .bottomSpaceToView(self.videoPlayer.videoControl.contentView, 0)
    .leftSpaceToView(self.videoPlayer.videoControl.contentView, 0)
    .rightSpaceToView(self.videoPlayer.videoControl.contentView, 0)
    .heightIs(44);
    
    [self.videoPlayer.videoControl.contentView bringSubviewToFront:self.videoPlayer.videoControl.underSlider];
    
    _commentBGView = [[UIView alloc] initWithFrame:self.view.bounds];
    _commentBGView.backgroundColor = [UIColor blackColor];
    _commentBGView.alpha = 0.2;
    _commentBGView.hidden = YES;
    UITapGestureRecognizer *tapGester = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(action_tapGester)];
    [_commentBGView addGestureRecognizer:tapGester];
    [self.view addSubview:_commentBGView];
    [self.view addSubview:self.sendCommentView];
    
}

//关闭右滑pop
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    return gestureRecognizer != self.navigationController.interactivePopGestureRecognizer;
}

- (void)action_leftButton:(UIButton *)sender{
    if (self.isModel) {
        [LPCostomPressentAnimationSimilarityPushAnimation backLastVc];
        [self dismissViewControllerAnimated:NO completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 初始化播放器

- (void)initVideoPlayer{
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.isPresented = NO;
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    // 播放指定 vid 的视频
    [self.videoPlayer setVid:self.model.TEACHERVIDEO];
    self.videoPlayer.model = self.model;
    [self.view addSubview:self.videoPlayer.view];
    [self.videoPlayer setParentViewController:self];
    // 需要保留导航栏
    [self.videoPlayer keepNavigationBar:YES];
    [self.videoPlayer setNavigationController:self.navigationController];
    
    // 设置附加组件
    [self.videoPlayer setHeadTitle:self.video.title];
    [self.videoPlayer setEnableDanmuDisplay:NO];      // 不显示弹幕按钮
    [self.videoPlayer setEnableRateDisplay:NO];       // 不显示播放速率按钮
    
    UIImage *logo = [UIImage imageNamed:@"pvlogo.png"];
    [self.videoPlayer setLogo:logo location:PvLogoLocationTopLeft size:CGSizeMake(70, 30) alpha:0.8]; // 设置logo
    
    // 开启片头播放
    // self.videoPlayer.teaserEnable = YES;
    
    // 自动续播, 是否继续上次观看的位置
    self.videoPlayer.autoContinue = YES;
    
    // 开启弹幕
    [self.videoPlayer enableDanmu:NO];
    
    // 是否开启截图
    self.videoPlayer.enableSnapshot = NO;
    
    // 设置是否自动播放，默认为YES
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:AUTOPLAY] isEqualToString:@"1"]) {
        self.videoPlayer.shouldAutoplay = YES;
        self.videoPlayerMeun.startButton.selected = YES;
    }else{
        self.videoPlayer.shouldAutoplay = NO;
        self.videoPlayerMeun.startButton.selected = NO;
    }
    /**
     *  ---- 回调代码块 ----
     */
    __weak typeof(self) weakSelf = self;
    [self.videoPlayer setPlayButtonClickBlock:^{
        weakSelf.videoPlayerMeun.startButton.selected = YES;
    }];
    [self.videoPlayer setPauseButtonClickBlock:^{
        weakSelf.videoPlayerMeun.startButton.selected = NO;
    }];
    [self.videoPlayer setFullscreenBlock:^{
        //NSLog(@"should hide toolbox in this viewcontroller if needed");
    }];
    [self.videoPlayer setShrinkscreenBlock:^{
        //NSLog(@"show toolbox back if needed");
        
    }];
    
    // 视频播放完成的回调代码块
    [self.videoPlayer setWatchCompletedBlock:^{
        weakSelf.videoPlayerMeun.startButton.selected = NO;
        [weakSelf SkinVideoViewControllerDelegate_isFullScreen:NO];
    }];
    
}

#pragma mark - 通知
- (void)currentTimeAndTotalTime:(NSNotification *)info{
    
    self.videoPlayerMeun.currentTime.text = info.object[@"currentTime"];
    self.videoPlayerMeun.totalTime.text = info.object[@"totalTime"];
}

- (void)IntroduceCell_reLoadTableViewCell:(NSNotification *)info{
    NSDictionary *dict = info.userInfo;
    NSString *synopsisIntroduce = [dict objectForKey:SynopsisIntroduce];
    NSString *teachIntroduce1 = [dict objectForKey:teachIntroduce];
    
    if ([synopsisIntroduce isEqualToString:@"1"]) {//课程简介展开
        _synopsisIntroduce_isUnfold = YES;
    }else{//课程简介收缩
        _synopsisIntroduce_isUnfold = NO;
    }
    if ([teachIntroduce1 isEqualToString:@"1"]) {//教师简介展开
        _teacherIntroduce_isUnfold = YES;
    }else{//教师简介收缩
        _teacherIntroduce_isUnfold = NO;
    }
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    
}

#pragma mark - 键盘处理

- (void)action_tapGester{
    [self.view endEditing:YES];
    
}

- (void)keyboardWillShow:(NSNotification *)notification {
    _commentBGView.hidden = NO;
    self.sendCommentView.hidden = NO;
    [self.view bringSubviewToFront:self.sendCommentView];
    
    CGFloat curkeyBoardHeight = [[[notification userInfo] objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue].size.height;
    
    NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //计算 视图应该移动的位置
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:interal animations:^{
        
        weakSelf.sendCommentView.frame = CGRectMake(0, [UIScreen zj_screenHeight] - weakSelf.sendCommentView.height - curkeyBoardHeight, [UIScreen zj_screenWith], weakSelf.sendCommentView.height);
    }];
}

- (void)keyboardWillDismiss:(NSNotification *)notification {
    _commentBGView.hidden = YES;
    self.sendCommentView.hidden = YES;
    NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //计算 视图应该移动的位置
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:interal animations:^{
        weakSelf.sendCommentView.frame = CGRectMake(0, [UIScreen zj_screenHeight], [UIScreen zj_screenWith], weakSelf.sendCommentView.height);
        
    }];
}




#pragma mark - 数据源获取


//获取上次视频播放时间
- (void)netWorking_lastVideo{
    NSString *time = [NSDateFormatter stringTimeWithDate:[NSDate date]];
    NSDictionary *dict = @{@"STUDENTID":ZJUSERINFORMODEL.CURRENT_USER_MODEL.ID,
                           @"COURSEWAREID":self.model.ID,
                           @"TIME":time,
                           @"ACCOUNTID":ZJUSERINFORMODEL.ORG_ACCOUNT.ID,
                           @"UNITID":ZJUSERINFORMODEL.CURRENT_DEPT_MODEL.ID};
    [NetWorkingManager postWithUrlString:[NetWorkingURL setVideoLogForMible] Parameter:dict Success:^(id object) {

    } Fail:^(id object) {
        
    }];
}

/**  获取评分信息  */

- (void)netGradeInfor{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"COURSEWAREID":self.model.ID, @"USER_ID": ZJUSERINFORMODEL.ORG_ACCOUNT.ID};
    [NetWorkingManager postWithUrlString:[NetWorkingURL getstresourcesactionEvaluatelistEvaluate] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {//
            weakSelf.gradeModel = [ZJSCSynopsisGradeModel yy_modelWithJSON:object];
            
            if (weakSelf.isScore) {
                NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:0];
                
                [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexpath,nil] withRowAnimation:UITableViewRowAnimationNone];
            }
        }
    } Fail:^(id object) {
        
    }];


}
//获取课程简介
- (void)networking_introduce{
    [self.dataArray removeAllObjects];
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"COURSEWARE_ID":self.model.ID, @"USER_ID": ZJUSERINFORMODEL.CURRENT_USER_MODEL.ID};
    [NetWorkingManager postWithUrlString:[NetWorkingURL courseware] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {//
            ZJSCSynopsisModel *model = [ZJSCSynopsisModel yy_modelWithJSON:object];
            [weakSelf.dataArray addObject:model];
            [weakSelf netWorking_correlation];
            weakSelf.isCollection = object[@"COURSEWARECOMMENT"][@"ISADD"];
            _COLLECTION_ID =[[object objectForKey:@"COURSEWARECOMMENT"] objectForKey:@"COLLECTION_ID"];
            if ([weakSelf.isCollection isEqualToString:@"0"]) {
                weakSelf.footerView.collectButton.selected = YES;
            }
        }
    } Fail:^(id object) {
        
    }];
}

//相关课程
- (void)netWorking_correlation{
    NSDictionary *dict = @{@"PAGE_NUMBER":@"1",
                           @"SHOW_NUMBER":@"3"};
    __weak typeof(self) weakSelf = self;
    [NetWorkingManager postWithUrlString:[NetWorkingURL listRecommend] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {//请求成功
            
            NSArray *array = [[NSArray yy_modelArrayWithClass:[ZJStudySpacialDetailModel class] json:object[@"ST_COURSEWARE"]] mutableCopy];
            [weakSelf.dataArray addObject:array];
            [weakSelf.tableView reloadData];
        }
        ;
    } Fail:^(id object) {
  
    }];
}

///课程推荐
- (void)netWorking_Recommend{
    NSDictionary *dict = @{@"PAGE_NUMBER":@"2",
                           @"SHOW_NUMBER":@"10"};
    __weak typeof(self) weakSelf = self;
    [NetWorkingManager postWithUrlString:[NetWorkingURL listRecommend] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {//请求成功
            
            NSArray *array = [[NSArray yy_modelArrayWithClass:[ZJStudySpacialDetailModel class] json:object[@"ST_COURSEWARE"]] mutableCopy];
            [weakSelf.tableFooterDataArray addObject:array];
            [weakSelf netWorking_Like];
        }
        ;
    } Fail:^(id object) {
        
    }];
}

///猜你喜欢
- (void)netWorking_Like{
    NSDictionary *dict = @{@"PAGE_NUMBER":@"3",
                           @"SHOW_NUMBER":@"10"};
    __weak typeof(self) weakSelf = self;
    [NetWorkingManager postWithUrlString:[NetWorkingURL listRecommend] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {//请求成功
            
            NSArray *array = [[NSArray yy_modelArrayWithClass:[ZJStudySpacialDetailModel class] json:object[@"ST_COURSEWARE"]] mutableCopy];
            [weakSelf.tableFooterDataArray addObject:array];
            weakSelf.tableFooterViwe.dataArray = weakSelf.tableFooterDataArray;
        }
        ;
    } Fail:^(id object) {
        
    }];
}

#pragma mark- ZJStudyCourseSynopsisTableViewCellDelegate
- (void)ZJStudyCourseSynopsisTableViewCellWithNumber:(NSString *)number{
    
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *paramer = [NSMutableDictionary dictionary];
    paramer[@"USER_ID"] = ZJUSERINFORMODEL.ORG_ACCOUNT.ID;
    paramer[@"COURSEWAREID"] = self.model.ID;
    paramer[@"ACCOUNTID"] = ZJUSERINFORMODEL.ORG_ACCOUNT.ID;
    paramer[@"UNITID"] = ZJUSERINFORMODEL.CURRENT_DEPT_MODEL.ID;
    paramer[@"ITEMNAMES"] = @"单项评分";
    paramer[@"ITEMSCORES"] = number;
    paramer[@"ITEMIDS"] = @"6";
    [NetWorkingManager postWithUrlString:[NetWorkingURL getstresourcesactionEvaluate] Parameter:paramer Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE integerValue] == 20000) {
            weakSelf.isScore = YES;
            [weakSelf netGradeInfor];
        }else{
            [YJProgressHUD showSuccess:@"评分失败" inview:[UIApplication sharedApplication].keyWindow];
        }
        
    } Fail:^(id object) {
        [YJProgressHUD showSuccess:@"评分失败" inview:[UIApplication sharedApplication].keyWindow];
    }];

}


#pragma mark - SkinVideoViewControllerDelegate 协议方法
//点击全屏
- (void)SkinVideoViewControllerDelegate_isFullScreen:(BOOL)isFullScreen{
    
    if (isFullScreen) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"UIMoviePlayerControllerDidEnterFullscreenNotification" object:nil];
        [self rotateScreen:isFullScreen];
        self.videoPlayer.view.sd_layout
        .topSpaceToView(self.view, 0)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 0)
        .heightIs(self.view.width / 16 * 9);
        [self.videoPlayer.view updateLayout];
        
        [self.view bringSubviewToFront:self.videoPlayer.view];
    }else{
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"UIMoviePlayerControllerDidExitFullscreenNotification" object:nil];
        [self rotateScreen:isFullScreen];
        self.videoPlayer.view.sd_layout
        .topSpaceToView(self.view, LP_TopHeight)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 0)
        .heightIs(self.view.width / 16 * 9);
        [self.videoPlayer.view updateLayout];
        [self.view bringSubviewToFront:self.videoPlayer.view];
    }
}
//旋转界面
- (void)rotateScreen:(BOOL)isLandscapeRight
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)])
    {
        NSNumber *num = [[NSNumber alloc] initWithInt:(isLandscapeRight?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait)];
        [[UIDevice currentDevice] performSelector:@selector(setOrientation:) withObject:(id)num];
        [UIViewController attemptRotationToDeviceOrientation];
        //这行代码是关键
    }
    SEL selector=NSSelectorFromString(@"setOrientation:");
    NSInvocation *invocation =[NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
    [invocation setSelector:selector];
    [invocation setTarget:[UIDevice currentDevice]];
    int val =isLandscapeRight?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait;
    [invocation setArgument:&val atIndex:2];
    [invocation invoke];
    [[UIApplication sharedApplication] setStatusBarHidden:isLandscapeRight withAnimation:UIStatusBarAnimationSlide];
}


#pragma mark - ZJVideoControllerMeunViewDelegate(播放控制器) 协议方法

- (void)ZJVideoControllerMeunViewDelegate_startButton:(UIButton *)sender{
    if (sender.selected) {
        [self.videoPlayer playButtonClick];
    }else{
        [self.videoPlayer pauseButtonClick];
    }
}

- (void)ZJVideoControllerMeunViewDelegate_backward:(UIButton *)sender{
    [self.videoPlayer progressSliderTouchBegan:self.videoPlayer.videoControl.underSlider.slider];
    self.videoPlayer.videoControl.underSlider.slider.value -=  30.0f;
    self.videoPlayerMeun.startButton.selected = YES;
    [self.videoPlayer progressSliderTouchEnded:self.videoPlayer.videoControl.underSlider.slider];
//    [self.videoPlayer setCurrentPlaybackTime:floor(self.videoPlayer.videoControl.slider.progressValue)];
}

- (void)ZJVideoControllerMeunViewDelegate_speed:(UIButton *)sender{
    [self.videoPlayer progressSliderTouchBegan:self.videoPlayer.videoControl.underSlider.slider];
     CGFloat max_Time = self.videoPlayer.videoControl.underSlider.slider.value + 30.0f;
   self.videoPlayerMeun.startButton.selected = YES;
    NSMutableDictionary *maxTimeDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:USER_DICT_MAX_PLAYTIME].mutableCopy;
   
    if (!maxTimeDict){
       self.videoPlayer.videoControl.slider.progressValue = 0;
        
    }else{
        
        double userDefaultsTime = [maxTimeDict[self.videoPlayer.vid] doubleValue];
        if (max_Time >= userDefaultsTime) {
            [YJProgressHUD showMsgWithoutView:MAXTIME_HINT];
            self.videoPlayer.videoControl.underSlider.slider.value = userDefaultsTime;
        }else{
             self.videoPlayer.videoControl.underSlider.slider.value = max_Time;
        }
    [self.videoPlayer progressSliderTouchEnded:self.videoPlayer.videoControl.underSlider.slider];

 }
}
#pragma mark - ZJStudyCoureFooterViewDelegate（下部footerView） 协议方法
/** 评论输入框 */
- (void)ZJStudyCoureFooterViewDelegate_commentTextButtonClick{
    self.sendCommentView.commentTextView.placeHolder = @"优质评论会被优先展示";
    _isCommentORNote = YES;
    _isCourseComment = YES;
    self.sendCommentView.hidden = NO;
    [self.sendCommentView.commentTextView.textView becomeFirstResponder];
}
/** 评论按钮 */
- (void)ZJStudyCoureFooterViewDelegate_commentButtonClick{//跳评论页面
    __weak typeof(self) weakSelf = self;
    StudyCourseQuestionsViewController *vc = [StudyCourseQuestionsViewController new];
    vc.model = self.model;
    vc.currTime = self.videoPlayer.currentTime;
    vc.block = ^(){//刷新tableview
        [weakSelf networking_introduce];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
/** 笔记按钮 */
- (void)ZJStudyCoureFooterViewDelegate_noteButtonClick{
    self.sendCommentView.commentTextView.placeHolder = @"请输入笔记内容";
    _isCommentORNote = NO;
    self.sendCommentView.hidden = NO;
    [self.sendCommentView.commentTextView.textView becomeFirstResponder];
}
/** 收藏按钮 */
- (void)ZJStudyCoureFooterViewDelegate_collectButtonClick{
    if ([self.isCollection isEqualToString:@"0"]) {//删除选学
        [self deleteStudy];
        return;
    }
    //加入选学
    __weak typeof(self) weakSelf = self;
    NSDictionary *paramer =
            @{@"USER_ID":[ZJUserInfoModel sharedUserInfo].CURRENT_USER_MODEL.ID,//当前用户id
             @"COURSEWARE_ID":self.model.ID,//课程id
             @"CATEGORY":@"0"
             };
    [NetWorkingManager postWithUrlString:[NetWorkingURL addCollection] Parameter:paramer Success:^(id object) {
        NetWorkModel *netmdoel = [NetWorkModel yy_modelWithJSON:object];
        if ([netmdoel.STATE isEqualToString:@"20000"]) {
            [YJProgressHUD showSuccess:@"收藏成功" inview:weakSelf.view];
            _COLLECTION_ID = [object objectForKey:@"COLLECTION_ID"];
            weakSelf.footerView.collectButton.selected = YES;
            weakSelf.isCollection = @"0";
        }else if([netmdoel.STATE isEqualToString:@"40001"]){
            [YJProgressHUD showSuccess:@"已加入选学" inview:weakSelf.view];
        }else{
        
             [YJProgressHUD showSuccess:@"收藏失败" inview:weakSelf.view];
        }
    } Fail:^(id object) {
        
    }];

}
///删除选学
- (void)deleteStudy{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"COLLECTION_ID":[NSString isNilStringReturnString:_COLLECTION_ID]};
    [NetWorkingManager postWithUrlString:[NetWorkingURL delCollection] Parameter:dict Success:^(id object) {
        NetWorkModel *netmdoel = [NetWorkModel yy_modelWithJSON:object];
        if ([netmdoel.STATE isEqualToString:@"20000"]) {
            [YJProgressHUD showSuccess:@"删除成功" inview:weakSelf.view];
            weakSelf.footerView.collectButton.selected = NO;
            weakSelf.isCollection = @"1";
        }else{
            [YJProgressHUD showSuccess:@"删除失败" inview:weakSelf.view];
        }
    } Fail:^(id object) {
        
    }];

}

#pragma mark - SendCommentViewDelegate(发送评论) 协议方法
//发送评论
- (void)sendButtonClick{
    [self.view endEditing:YES];
    NSDictionary *dict = @{};
    if (_isCommentORNote) {//评论
            dict = @{@"USERID":[ZJUserInfoModel sharedUserInfo].CURRENT_USER_MODEL.ID,//当前用户id
                     @"COURSEWAREID":self.model.ID,//课程id
                     @"ACCOUNTID":[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.ID,//账户id
                     @"CONTENT":self.sendCommentView.commentTextView.textView.text,//评论内容
                     @"VIDEOSTAMP":@(self.videoPlayer.currentTime),
                     @"UNITID":[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.CURRENTIDENTITY //机构id
                     };
        
        [self netWorkingCommentWithDict:dict];
        
    }else{//笔记
        
        [self netWorkingNote];
    }
}
//发送评论的网络请求
//评论
- (void)netWorkingCommentWithDict:(NSDictionary *)dict{
    [YJProgressHUD show:@"" inView:self.view mode:YJProgressModeLoading];
    __weak typeof(self) weakSelf = self;
    
    [NetWorkingManager postWithUrlString:[NetWorkingURL addClassFAQ] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {//评论成功
            [YJProgressHUD showMsgWithoutView:@"评论成功"];
            [weakSelf networking_introduce];
        }else{
            
            [YJProgressHUD showMsgWithoutView:@"评论失败"];
        }
    } Fail:^(id object) {
        [YJProgressHUD showMsgWithoutView:@"评论失败"];
    }];
}
//写笔记的网络请求

//笔记
- (void)netWorkingNote{
    [YJProgressHUD show:@"" inView:self.view mode:YJProgressModeLoading];
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"USER_ID":[ZJUserInfoModel sharedUserInfo].CURRENT_USER_MODEL.ID,//用户id
                           @"VIDEO_STAMP":@(self.videoPlayer.currentTime),//视频时间
                           @"COURSEWARE_ID":self.model.ID,//课程id
                           @"UNITID":[ZJUserInfoModel sharedUserInfo].DEPT_MODEL_JOB.ID,//机构id
                           @"NOTE_CONTENT":self.sendCommentView.commentTextView.textView.text};//笔记内容
    [NetWorkingManager postWithUrlString:[NetWorkingURL courseNote] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        [YJProgressHUD hide];
        if ([model.STATE isEqualToString:@"20000"]) {//记笔记成功
            [weakSelf networking_introduce];
        }else{
            [YJProgressHUD showMsgWithoutView:@"记笔记失败"];
        }
    } Fail:^(id object) {
        [YJProgressHUD showMsgWithoutView:@"记笔记失败"];
    }];
    
}

#pragma mark - ZJCorrelationCourseTableViewCellDelegate(相关课程) 协议方法
- (void)ZJCorrelationCourseTableViewCellDelegate_model:(ZJStudySpacialDetailModel *)model{
    StudyCoureVideoViewController *vc = [StudyCoureVideoViewController new];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];

}

#pragma mark - ZJCRImageViewAndLabelViewDelegate(猜你喜欢、课程推荐) 协议方法
- (void)ZJCourseRecommendViewDelegate_model:(ZJStudySpacialDetailModel *)model{

    StudyCoureVideoViewController *vc = [StudyCoureVideoViewController new];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - UITableView 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {//课程简介
        ZJStudyCourseSynopsisTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SYNOPSISSCECTIONVIEW forIndexPath:indexPath];
        cell.clickNumberString = self.model.CLICKRATE;
        cell.model.synopsisIntroduce_isUnfold = _synopsisIntroduce_isUnfold;
        cell.model.teacherIntroduce_isUnfold = _teacherIntroduce_isUnfold;
        cell.gradeModel = self.gradeModel;
        cell.model = self.dataArray[indexPath.row];
        cell.delegate = self;
        return cell;
    }else{
        ZJCorrelationCourseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CorrelationCourseCELL forIndexPath:indexPath];
        cell.delegate = self;
        cell.dataArray = self.dataArray[indexPath.row];
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == 0) {//课程简介
        ZJStudyCourseSynopsisTableViewCellModel *model = [ZJStudyCourseSynopsisTableViewCellModel new];
        model.model = self.dataArray[indexPath.row];
        model.model.synopsisIntroduce_isUnfold = _synopsisIntroduce_isUnfold;
        model.model.teacherIntroduce_isUnfold = _teacherIntroduce_isUnfold;
        [cellHeightDict setValue:@(model.cellHeight) forKey:[NSString stringWithFormat:@"%ld",indexPath.row]];
        
        return model.cellHeight;
    }else{
        NSArray *array = self.dataArray[indexPath.row];
        return array.count * 120 * [UIScreen zj_screenHScale] + 44 * [UIScreen zj_screenHScale];
    }
}




#pragma mark - Setter
#pragma mark - Getters

- (UITableView *)tableView{
    if (_tableView == nil){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.videoPlayer.view.bottom, self.view.width, self.footerView.y - self.videoPlayer.view.bottom)  style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    
        [_tableView  registerClass:[ZJStudyCourseSynopsisTableViewCell class] forCellReuseIdentifier:SYNOPSISSCECTIONVIEW];
        [_tableView registerClass:[ZJCorrelationCourseTableViewCell class] forCellReuseIdentifier:CorrelationCourseCELL];
        _tableView.tableFooterView = self.tableFooterViwe;
    
    }
    return _tableView;
}


- (NSMutableArray *)dataArray{
    if (_dataArray == nil){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray *)tableFooterDataArray{
    if (_tableFooterDataArray == nil){
        _tableFooterDataArray = [NSMutableArray array];
    }
    return _tableFooterDataArray;
}

- (ZJStudyCoureFooterView *)footerView{
    if (_footerView == nil){
        _footerView = [[ZJStudyCoureFooterView alloc]initWithFrame:CGRectMake(0, self.view.height - 49, self.view.width, 49)];
        _footerView.delegate = self;
    }
    return _footerView;
}

- (SkinVideoViewController *)videoPlayer{
    if (!_videoPlayer) {
        CGFloat width = self.view.bounds.size.width;
        _videoPlayer = [[SkinVideoViewController alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + LP_TopHeight, width, width*(9.0/16.0))];
        [_videoPlayer configObserver];
        //允许滑动
        _videoPlayer.selectedIndex = _selectedIndex;
        _videoPlayer.videoControl.hidden = NO;
        _videoPlayer.fulldelegate = self;
    }
    return _videoPlayer;
}

- (ZJVideoControllerMeunView *)videoPlayerMeun{
    if (_videoPlayerMeun == nil){
        CGFloat width = self.view.bounds.size.width;
        _videoPlayerMeun = [[ZJVideoControllerMeunView alloc] initWithFrame:CGRectMake(0, width*(9.0/16.0) - 44, self.view.width, 44)];
        _videoPlayerMeun.backgroundColor = [UIColor whiteColor];
        _videoPlayerMeun.delegate = self;
        _videoPlayerMeun.startButton.selected = YES;
    
    }
    return _videoPlayerMeun;
}


- (SendCommentView *)sendCommentView{
    if (_sendCommentView == nil){
        _sendCommentView = [[SendCommentView alloc]initWithFrame:CGRectMake(0, [UIScreen zj_screenHeight], [UIScreen zj_screenWith], [UIScreen zj_screenHeight] * 0.2)];
        _sendCommentView.commentDelegate = self;
    }
    return _sendCommentView;
}

- (ZJCourseRecommendView *)tableFooterViwe{
    if (_tableFooterViwe == nil){
        _tableFooterViwe = [[ZJCourseRecommendView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 194 * [UIScreen zj_screenHScale])];
        _tableFooterViwe.delegate = self;
    }
    return _tableFooterViwe;
}
@end
